from typing import List

from sqlalchemy import insert, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from app.database.models import User


async def get_users(session: AsyncSession) -> List[User]:
    q = select(User)

    res = await session.execute(q)

    return res.scalars().all()


async def get_user(
    session: AsyncSession, telegram_id: int, joined: bool = False
) -> User:
    q = select(User).where(User.telegram_id == telegram_id)

    if joined:
        q = q.options(
            joinedload(User.accounts),
            joinedload(User.documents),
            joinedload(User.whitepages),
            joinedload(User.unique),
            joinedload(User.tasks),
        )

    res = await session.execute(q)

    return res.scalar()


async def add_user(session: AsyncSession, telegram_id: int) -> None:

    user = User(telegram_id=telegram_id)

    session.add(user)

    await session.commit()


# async def update_user(
#     session: AsyncSession, column_name: str, value: str, telegram_id: int
# ) -> None:
#     await session.execute(
#         update(User)
#         .where(User.telegram_id == telegram_id)
#         .values(
#             {
#                 column_name: value,
#             }
#         )
#     )
#     await session.commit()


async def add_user_proxies(
    session: AsyncSession, telegram_id: int, proxies: str
) -> None:
    q = update(User).filter(User.telegram_id == telegram_id).values(proxies=proxies)
    await session.execute(q)

    await session.commit()
